package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.sqfw.dto.SqfwSummaryPdfExcelCollForAdminDTO;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.SqfwCheckRecordForAdminService;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.SqfwSummaryForAdminService;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.AuthorityUtil;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: SqfwServicerecordForAdminController
 * @description: 入户调查（后台管理系统）
 * @author: LJT
 * @create: 2023-11-03 10:20
 **/
@IocBean
@At("/platform/sqfw/checkRecord")
@ApiDefinition(tag = "入户调查")
@Slf4j
public class SqfwCheckRecordForAdminController {

    @Inject
    private SqfwSummaryForAdminService sqfwSummaryForAdminService;

    @Inject
    private SqfwCheckRecordForAdminService sqfwCheckRecordForAdminService;

    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SysUserService sysUserService;

    /**
     * 删除巡查记录
     *
     * @param id
     * @return
     */
    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除表数据")
    @SLog(tag = "删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id) {
        Sqfw_formSummary sqfwFormSummary = sqfwFormSummaryService.fetch(id);
        if (sqfwFormSummary == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwCompleteflowService.deleteAndUpdateWO(sqfwFormSummary.getSqfwFlowId());
        return Result.success();
    }


    /**
     * 巡查记录列表查询（用于后台管理系统）
     */
    @At("/listForHouseSurvey")
    @Ok("json")
    @POST
    @ApiOperation(name = "后台管理系统入户调查列表查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @ApiResponses(
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SLog(tag = "后台管理系统入户调查列表查询", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> listForHouseSurvey(@Param("..") Sqfw_formSummaryForAdminVO bean) {
        return sqfwCheckRecordForAdminService.listForHouseSurvey(bean, bean.getPageOrderName(), bean.getPageOrderBy());
    }

    /**
     * 前台勾选下载pdf合计
     *
     * @param conditionList
     */
    @At("/generateServiceRecordPdfColl")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成pdf合集")
    @SaCheckLogin
    public Result<?> generateServiceRecordPdfColl(@Param("conditionList") List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList) {
        String pdfUrl = sqfwSummaryForAdminService.generateServiceRecordPdfColl(conditionList);
        log.info("generateServiceRecordPdfColl url: {}", pdfUrl);
        return Result.data(pdfUrl);
    }

    /**
     * 前台勾选下载excel合集
     *
     * @param conditionList
     * @param fileIndex
     * @param excelType
     * @return
     */
    @At("/generateServiceRecordExcelColl")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成Excel合集")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelColl(@Param("conditionList") List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList, @Param("fileIndex") Integer fileIndex, @Param("excelType") String excelType) {
        if (conditionList.size() <= 0) {
            return Result.error("无匹配记录！");
        }
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateCheckRecordExcelColl("", conditionList, userId, fileIndex, excelType);
        return Result.data(excelUrl);
    }

    /**
     * 根据条件下载pdf集合
     *
     * @param bean
     * @param pageOrderName
     * @param pageOrderBy
     * @return
     */
    @At("/generateServiceRecordPdfCollByCond")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据条件下载pdf集合")
    @ApiFormParams(
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SLog(tag = "根据条件下载pdf集合", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordPdfCollByCond(@Param("..") Sqfw_formSummaryForAdminVO bean, String pageOrderName, String pageOrderBy) {
        AuthorityUtil.checkFormSummaryAreaPermission(bean);
        List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList = sqfwCheckRecordForAdminService.getPdfExcelFileDownSumIdList(bean, pageOrderName, pageOrderBy);
        if (conditionList.size() <= 0) {
            return Result.error("无匹配记录！");
        }
        String pdfUrl = sqfwSummaryForAdminService.generateServiceRecordPdfColl(conditionList);
        return Result.data(pdfUrl);
    }

    /**
     * 根据条件下载Excel集合
     *
     * @param bean
     * @param pageOrderName
     * @param pageOrderBy
     * @return
     */
    @At("/generateServiceRecordExcelCollByCond")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据条件下载Excel集合")
    @ApiFormParams(
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelCollByCond(@Param("..") Sqfw_formSummaryForAdminVO bean, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy, @Param("fileIndex") List<String> fileIndex, @Param("excelType") String excelType) {
        AuthorityUtil.checkFormSummaryAreaPermission(bean);
        List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList = sqfwCheckRecordForAdminService.getPdfExcelFileDownSumIdList(bean, pageOrderName, pageOrderBy);
        if (conditionList.size() <= 0) {
            return Result.error("无匹配记录！");
        }
        List<String> sumIds = conditionList.stream().map(SqfwSummaryPdfExcelCollForAdminDTO::getSumId).collect(Collectors.toList());
        String userId = SecurityUtil.getUserId();
        Sys_user sysUser = sysUserService.fetch(userId);
        String pdfUrl = sqfwSummaryForAdminService.generateServiceSummaryExcelCollZipForBM("入户调查", sysUser.getCounty(), sumIds, userId, null, excelType);
        return Result.data(pdfUrl);
    }

    /**
     * 供小程序使用，无权限，只需要登陆即可
     * 后台管理安全检查、垃圾分类、入户调查检查excel是否有数统一入口
     *
     * @return 返回url
     */
    @At("/getDownloadExcelTypeFromAdmin")
    @Ok("json")
    @POST
    @ApiOperation(name = "后台管理安全检查、垃圾分类、入户调查检查excel是否有数统一入口")
    @SLog(tag = "后台管理安全检查、垃圾分类、入户调查检查excel是否有数统一入口", value = "")
    @SaCheckLogin
    public Result<?> getDownloadExcelTypeFromAdmin(@Param("conditionList") List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList, @NotNull @Param("serviceType") String serviceType, @Param("companyName") String companyName, @Param("..") Sqfw_formSummaryForAdminVO bean, @Param("queryEntry") String queryEntry) {
        log.info("getDownloadExcelTypeFromAdmin info param conditionList: {},serviceType:{},companyName:{}", conditionList, serviceType, companyName);
        if (SupportBusinessTypeEnum.SAFE_CHECK.getName().equals(serviceType)) {
            if (StringUtils.isBlank(companyName)) {
                throw new ServiceException("街道名称不能为空！");
            }
        }
        return Result.data(sqfwFormSummaryService.getDownloadExcelTypeFromAdmin(conditionList, serviceType, companyName, bean,queryEntry));
    }

    /**
     * 根据上传的ExcelType 下载模板
     *
     * @param sqfwId
     * @param excelType
     * @param fileIndex
     * @return
     * @auth zhangp
     * @Date 2023-11-23
     */
    @At("/getDownloadTemplateFromAdmin")
    @Ok("json")
    @POST
    @ApiOperation(name = "模板下载")
    @SLog(tag = "模板下载", value = "")
    @ApiFormParams({@ApiFormParam(name = "sqfwId", description = "服务ID"), @ApiFormParam(name = "excelType", description = "EXCEL类型"), @ApiFormParam(name = "excelType", description = "文件索引")})
    @SaCheckLogin
    public Result<?> getDownloadTemplateFormExcelType(@Param("sqfwId") String sqfwId, @NotNull @Param("excelType") String excelType, @Param("fileIndex") Integer fileIndex, @Param("serviceType") String serviceType, @Param("companyName") String companyName) {
        log.info("getDownloadTemplateFormExcelType info param:sqfwId:{}, excelType: {},companyName:{}", sqfwId, excelType, companyName);
        return Result.data(sqfwFormSummaryService.getDownloadTemplateFormExcelType(sqfwId, fileIndex, excelType, null, serviceType, companyName));
    }

    @At("/updateHouseInfo")
    @Ok("json")
    @POST
    @ApiOperation(name = "入户调查信息更新")
    @ApiFormParams(implementation = Sqfw_formSummaryForAdminVO.class)
    @SLog(tag = "入户调查信息更新：", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> updateHouseInfo(@Param("..") Sqfw_formSummaryForAdminVO sqfwFormSummaryForAdminVO) {
        log.info("SqfwCheckRecordForAdminController updateHouseInfo userName: {}, param: {}", SecurityUtil.getUserUsername(), JSONObject.toJSONString(sqfwFormSummaryForAdminVO));
        sqfwSummaryForAdminService.updateSummaryInfo(sqfwFormSummaryForAdminVO);
        return Result.success();
    }
}
